
import express, { Request, Response } from "express"
import { AccountContext } from "../context/AccountContext"
import { Token } from "../dao/Token"
import { checkError, checkToken } from "../utils/token"
import { LoginParam, serviceConfig } from "@Tea/model"

const LoginRouter = express.Router()

LoginRouter.post("/login", async (req: Request, res: Response) => {
  const loginParam = req.body as LoginParam
  try {
    const accoutCxt = AccountContext.getInstance()
    
    const data = (await accoutCxt.verify(loginParam))[0][0]
    
    if (data) {
      if (!data.enable) {
        res.send({
          code: 0,
          msg: "账号被禁用",
        })

        return
      }
      console.log(data);
      
      if (data.type !== "admin") {
        res.send({
          code: 0,
          msg: "无权限",
        })

        return
      }
      const token = Token.getInstance()
      const TokenObject = token.refreshToken(data.userId)
      
      res.cookie(`${serviceConfig.systemTokenCode}`, TokenObject.token)

      res.send({
        code: 1,
        data: data,
      })

    } else {
      res.send({
        code: 0,
        msg:"账号未注册"
      })
    }
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg: checkError(e)
    })
  }
})

LoginRouter.delete("/loginOut", checkToken, async (req: Request, res: Response) => {
  try {
    const accoutCxt = AccountContext.getInstance()
    const result = accoutCxt.loginOut(req.cookies[serviceConfig.systemTokenCode])

    if (result) {
      res.send({
        code: 1,
        msg: "退出登录成功"
      })
    } else {
      res.status(401).send({
        code: 0,
        msg:"未发现登录信息"
      })
    }
     
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg: checkError(e)
    })
  }
})


export default LoginRouter